<template>
  <div class="sign">
    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="80px" class="sign-container">
      <el-form-item label="用户名" prop="userName">
        <el-input v-model="ruleForm.userName"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="ruleForm.password"></el-input>
      </el-form-item>
      <el-form-item class="sign-info">
        <p>没有账号？前往<span @click="signUp">注册</span></p>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')">登陆</el-button>
        <el-button @click="resetForm('ruleForm')">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
  import {setStore, getStore} from "../config/mUtils";

  export default {
    name: "signIn",
    data() {
      return {
        ruleForm: {
          userName: '',
          password: '',
          checkPass: ''
        },
        rules: {
          userName: [
            { required: true, message: '请输入用户名', trigger: 'blur' },
            { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
          ],
          password: [
            { required: true, message: '请输入密码', trigger: 'blur' },
            { min: 6, max: 10, message: '长度在 6 到 10 个字符', trigger: 'blur' }
          ]
        }
      }
    },
    created() {
      if (getStore('userName')) {
        this.$message({
          message: '存在已登录账号！',
          type: 'success'
        });
        setTimeout(() => {
          this.$router.push('/');
        }, 800);
      }
    },
    methods: {
      signUp() {
        this.$router.push('/signUp');
      },
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.$message({
              message: '登陆成功',
              type: 'success'
            });
            setStore('userName', this.ruleForm.userName);
            setTimeout(() => {
              this.$router.push('/');
            }, 800);
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      resetForm(formName) {
        this.$refs[formName].resetFields();
      }
    }
  }
</script>
